﻿using Easy.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace Easy.Domain.Core.Query
{
    class SqlHelper
    {
        private readonly string _connectionString;

        public SqlHelper(string connectionString)
        {
            CheckHelper.NotNull(connectionString, "connectionString");

            _connectionString = connectionString;
        }

        public DataSet ExecuteQuery(string sql, CommandType cmdType, Dictionary<string, object> parameters = null)
        {
            CheckHelper.NotEmpty(sql, "sql");

            SqlConnection connection = new SqlConnection(_connectionString);

            SqlCommand cmd = connection.CreateCommand();
            cmd.CommandType = cmdType;
            cmd.CommandText = sql;

            if (parameters != null && parameters.Count > 0)
            {
                var sqlParameters = GetSqlParameters(parameters);

                cmd.Parameters.AddRange(sqlParameters);
            }

            DataSet dataSet = new DataSet();

            try
            {
                connection.Open();

                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    da.Fill(dataSet);
                }
            }
            finally
            {
                cmd.Dispose();
                connection.Close();
            }

            return dataSet;
        }

        private static SqlParameter[] GetSqlParameters(Dictionary<string, object> parameters)
        {
            List<SqlParameter> sqlParameterlst = new List<SqlParameter>();

            foreach (var param in parameters)
            {
                string paramKey = param.Key.StartsWith("@") ? param.Key : "@" + param.Key;

                sqlParameterlst.Add(new SqlParameter(paramKey, param.Value ?? DBNull.Value));
            }

            return sqlParameterlst.ToArray();
        }
    }
}
